package com.rent.common.storage;


import com.rent.common.util.FileTypeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@Service
@ConditionalOnProperty(name = "rent.upload.type", havingValue = "local")
public class LocalStorageService implements com.rent.common.service.StorageService {

    @Value("${rent.upload.local.base-folder}")
    private String baseFolder;
    @Value("${rent.upload.local.base-url}")
    private String baseUrl;

    @PostConstruct
    public void init() {
        File dir = new File(baseFolder);
        if (!dir.exists()) dir.mkdirs();
    }

    @Override
    public String upload(String prefix,MultipartFile file) throws IOException {
        // 1. 校验
        FileTypeUtil.assertAllow(file);
        // 2. 生成路径
        String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        String newName = UUID.randomUUID() + "." + StringUtils.getFilenameExtension(file.getOriginalFilename());
        File targetFolder = new File(baseFolder, datePath);
        File targetFile = new File(targetFolder, newName);
        FileUtils.forceMkdirParent(targetFile);
        // 3. 落盘
        file.transferTo(targetFile);
        // 4. 返回 url
        return baseUrl + "/" + datePath + "/" + newName;
    }

    @Override
    public void delete(String filePath) {
        String relative = filePath.replace(baseUrl, "");
        File f = new File(baseFolder, relative);
        if (f.exists() && !f.delete()) {
            log.warn("delete file failed: {}", f.getAbsolutePath());
        }
    }
}
